package com.hyzx.qbasic.admin.domain.repository.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hyzx.qbasic.admin.domain.dao.RoleMapper;
import com.hyzx.qbasic.admin.model.po.RolePO;
import com.hyzx.qbasic.admin.domain.repository.IRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * Created by 黄江华 on 2017/9/29
 */

@Repository
public class RoleRepositoryImpl implements IRoleRepository {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public Set<String> getUserRoleNameList(int userId) {
        return roleMapper.getUserRoleNameList(userId);
    }

    @Override
    public List<RolePO> getAllRoleList() {
        return roleMapper.getAllRoleList();
    }

    @Override
    public PageInfo<RolePO> getPagedRoleList(int pageNum, int pageSize, String roleName) {
        PageInfo pageInfo = PageHelper.startPage(pageNum, pageSize)
                .doSelectPageInfo(() -> roleMapper.getPagedRoleList(roleName));

        return pageInfo;
    }

    @Override
    @Transactional
    public boolean addRole(RolePO role, List<Integer> resourceList) {
        int addRoleResult = roleMapper.addRole(role);
        if (!CollectionUtils.isEmpty(resourceList))
            roleMapper.addRoleResources(role.getRoleId(), resourceList);

        return addRoleResult > 0;
    }

    @Override
    @Transactional
    public boolean deleteRole(List<Integer> roleIdList) {
        int deleteRoleResult = roleMapper.deleteRole(roleIdList);
        roleMapper.deleteRoleResources(roleIdList);
        roleMapper.deleteRoleUsers(roleIdList);

        return deleteRoleResult > 0;
    }

    @Override
    @Transactional
    public boolean editRole(RolePO role, List<Integer> resourceList) {
        int editRoleResult = roleMapper.editRole(role);
        roleMapper.deleteRoleResources(Arrays.asList(role.getRoleId()));
        if (!CollectionUtils.isEmpty(resourceList))
            roleMapper.addRoleResources(role.getRoleId(), resourceList);

        return editRoleResult > 0;
    }

    @Override
    public List<Integer> getRoleResources(int roleId) {
        return roleMapper.getRoleResources(roleId);
    }

    @Override
    public RolePO getRoleInfo(int roleId) {
        return roleMapper.getRoleInfo(roleId);
    }
}
